Ext.ns('ru.proburo.oms.order.components');
/**
 * @class ru.proburo.oms.order.components.Detail
 * @extends Ext.Panel
 */
ru.proburo.oms.order.components.Detail = Ext.extend(Ext.Panel, {
	
	readonly: false,
	
	constructor: function(config)
	{
		config = config || {};
		
		this.record     = config.record;
		this.readonly  = (this.record.data.status == 10);
		
		this.form = new ru.proburo.oms.order.components.form.Panel({
			region:     'north',
			bodyStyle:  'background-color: #DEECFD;',
            labelWidth: 125,
            height: 	208,
			
			record:     this.record
		});
		
		this.grid = new ru.proburo.oms.order.components.grid.EditableList({
			region:   'center',
			tbar: 	  this.initTBar(),
			
			record:   this.record,
			readonly: this.readonly
		})
		
		Ext.applyIf(config, {
			layout:   'border',
            closable: true,
            items: [
				this.form,
				this.grid
			]
		});
		
		ru.proburo.oms.order.components.Detail.superclass.constructor.call(this, config);
	},
	
	initComponent: function()
	{
		ru.proburo.oms.order.components.Detail.superclass.initComponent.call(this);
		
		// TODO: refactory
		if(false === Ext.isAir)
		{
			this.form.on('afterrender', function(form){
				form.getForm().findField('customer_id').on('change', this._onCustomerChange, this);
			}, this, {single: true});
		}
	},
	
	initEvents: function()
	{
		ru.proburo.oms.order.components.Detail.superclass.initEvents.call(this);
		
		this.addEvents({
            'change':      	   true,
			'save':        	   true,
			'submit':		   true,
			'exception':	   true,
			'selectionchange': true
		});
        
		this.relayEvents(this.form, ['change']);
		this.relayEvents(this.grid, ['change', 'selectionchange', 'save']);
		
		this.record.store.on({
			'update': this._onRecordUpdate,
			'remove': this._onRecordRemove,
			scope: this
		});
		
		this.form.on({
			'render': this._doUpdateState,
			scope: this
		});
		this.grid.store.on({
			'load': this._doUpdateState,
			scope: this
		});
		
		this.on({
			'change': 			this._onChange,
			'save':    		    this._onSave,
			'submit': 			this._onSubmit,
			'exception':		this._onException,
			'selectionchange': 	this._onSelectionChange,
			'beforeclose': 		this._onBeforeClose,
			'close': 			this._onClose,
			
			scope: this
		});
	},
	
	initTBar: function()
	{
		this.saveAction = new Ext.Action({
			text: 	  'Сохранить',
			tooltip:  'Сохранить заказ',
			iconCls:  'silk-disk',
			disabled: true,
			
			handler:  this._doSave,
			scope: 	  this
		});
		
		this.submitAction = new Ext.Action({
			text: 	  'Отправить',
			tooltip:  'Отправить заказ',
			iconCls:  'silk-email-go',
			disabled: true,
			
			handler:  this._doSubmit,
			scope: 	  this
		});
		
		this.exportAction = new Ext.Action({
			text: 	  'Экспорт',
			tooltip:  'Экспортировать заказ',
			iconCls:  'silk-table-go',
			disabled: true,
			
			handler:  this._doExport,
			scope:    this
		});
		
        this.removeRowAction = new Ext.Action({
			text:     'Удалить строки',
			tooltip:  'Удалить выбранные позиции из заказа',
			iconCls:  'silk-package-delete',
			disabled: true,
			
			handler:  this._doRemoveRows,
			scope:    this
		});
		
		if(Ext.isAir)
		{
			return [
				this.removeRowAction,
				'->',
				this.saveAction,
				
				this.exportAction
			];
			
		}
		else
		{
			return [
				this.removeRowAction,
				'->',
				this.saveAction,
				
				this.submitAction
			];
		}
	},
	
	/**
	 * action handlers
	 */
	
	// private
	_doSave: function(b, e)
	{
		this.save();
	},
	
	// private
	_doSubmit: function(b, e)
	{
		this.submit();
	},
	
	// private
	_doExport: function(b, e)
	{
		var exporter = new ru.proburo.oms.components.Exporter();
		exporter.save(this.record, this.grid.store, 'csv');
	},
	
	// private
	_doRemoveRows: function(b, e)
	{
		this.grid.removeSelected();
	},
	
	/**
	 * internal routines
	 */
	// private
	_doUpdateState: function()
	{
		var ro = this.readonly;
		
		this.form.setDisabled(ro);		
		this.grid.getColumnModel().setEditable(5, !ro);
		
		this.saveAction.setHidden(ro);
		this.removeRowAction.setHidden(ro);
		this.submitAction.setHidden(ro);
		this.exportAction.setHidden(ro);
		
		this.setIconClass(true === this.readonly ? 'silk-table-key' : 'silk-table');
		this.setTitle(this.renderTitle());		
		
		this.saveAction.setDisabled(!(this.isDirty() && this.isValid()));
		
		this.submitAction.setDisabled(!(this.form.isValid() && this.grid.store.getCount() > 0));
		this.exportAction.setDisabled(!(this.form.isValid() && this.grid.store.getCount() > 0));
		
		// TODO: add|remove option from "add to"
	},

    // private
    _doClose: function()
	{
        this.fireEvent('close', this);
        this.destroy();
    },
	
	// private
	_submit: function(b, e)
	{
		this.setReadonly(true);
		
		this.form.getForm().doAction('submit', {
			method:  'POST',
			url:     '/services/order/list.json',
			timeout: 100,
			reset:   false,
			params:  params = {
				xaction: 'submit',
				id:      this.record.get('id')
			},
			success: function(form, action){
				this.fireEvent('submit', this, form, action);
			},
			failure: function(form, action){
				this.fireEvent('exception', this, form, action);
				this.setReadonly(false);
			},
			scope: this
		});
	},
	
	
	
	renderTitle: function(brief)
	{
		var title = 'Заказ'
		
		if(true == this.record.phantom)
		{			
			if(this.activator.createdOrders > 1)
			{
				title += ' (' + (Number(this.activator.createdOrders)-1) + ')';
			}
		}
		else
		{
			title += ' №' + this.record.get('id');
		}
		
		// TODO: summ on mouseover
		/*
		title += ', ' + Ext.util.Format.ruMoney(this.record.get('summ')) + ' <i>руб.</i>';
		*/
		
		if(!brief && this.isDirty())
		{
			title += ' *';
		}
		
		return title;
	},
	
	setReadonly: function(bool)
	{
		this.readonly = bool;
		
		this._doUpdateState();
	},
	
	addRecords: function(records)
	{
		if(this.readonly)
		{
			console.warn('cannot add records to readonly order.');
			return;
		}
		
		this.grid.addRecords(records);
	},
	
	
	
	save: function(callback, scope)
	{
		if(this.readonly)
		{
			console.warn('readonly order cannot be saved.');
			return;
		}
		
        if(callback)
		{
			this.on('save', callback, scope, {single:true});
        }
		
		if(this.form.isDirty() || this.isPhantom())
		{
			this.form.save(function(){
				if(this.grid.isDirty())
				{
					this.grid.save();
				}
				else
				{
					this.fireEvent('save', this);
				}
			}, this);
		}
		else
		{
			this.grid.save();
		}
	},
	
	submit: function()
	{
		if(this.readonly)
		{
			console.warn('readonly order cannot be sent.');
			return;
		}
		
		if(this.grid.store.getCount() < 1)
		{
			console.warn('order without lines cannot be sent.');
			return;
		}
		
		if(true == this.isDirty())
		{
			this.save(this._submit, this);
		}
		else
		{
			this._submit();
		}
	},
	
	close: function(callback, scope)
	{
        if(false !== this.fireEvent('beforeclose', this))
		{
            if(true === this.hidden)
			{
                this._doClose();
            }
			else
			{
				this.on('hide', this._doClose, this, {single:true});
                this.hide();
            }
        }
    },
	
	
	
	isPhantom: function()
	{
		return !!this.record.phantom;
	},
	
	isDirty: function()
	{
		return this.form.isDirty() || this.grid.isDirty();
	},
	
	isValid: function()
	{
		return this.form.isValid() && this.grid.isValid();
	},
	
	
	
	/**
	 * Event listeners
	 */
	
	// private
	_onRecordUpdate: function()
	{
		
	},
	
	// private
	_onRecordRemove: function()
	{
		
	},
	
	// private
    _onBeforeClose: function()
	{
		if(this.isDirty())
		{
			var handler = function(b){
				if('no' === b)
				{
					this._doClose();
				}
				else if('yes' === b)
				{
					this.on('save', this._doClose, this, {single: true});
					this.save();
				}
			};
			
			Ext.MessageBox.show({
				title:   'Сохранить изменения?',
				msg: 	 'Заказ ' + this.record.get('id') + ' не был сохранен. <br />Вы желаете сохранить изменения?',
				icon: 	 Ext.MessageBox.QUESTION,
				buttons: Ext.MessageBox.YESNOCANCEL,
				fn:      handler,
				scope: 	 this
			});
			
			return false;
		}
		
		return true;
	},
	
	// private
	_onChange: function()
	{
		this._doUpdateState();
	},
	
	// private
	_onSave: function()
	{
		//this.record.set('status', 10);
		//this.record.commit();
		
		this._doUpdateState();
	},
	
	// private
	_onSubmit: function(form, action)
	{
		this.record.set('foreign_id', action.result.foreign_id);
		this.record.set('status', 10);
		this.record.commit();
		
		this._doUpdateState();
	},
	
	// private
	_onException: function(panel, form, action)
	{
		var message = action.result ? action.result.message : 'Ошибка соединения';
		console.warn(message);
	},
	
	// private
	_onSelectionChange: function(sModel)
	{
		if(sModel.getCount())
		{
			this.removeRowAction.enable();
		}
		else
		{
			this.removeRowAction.disable();
		}
	},
	
	// private
    _onClose: function()
	{
		if(this.record.store && this.record.store.phantom)
		{
			this.record.store.remove(this.record);
		}
	},
	
	
	
	
	
	
	/**
	 * TODO: refactory
	 */
	// private
	_onCustomerChange: function(field, newValue, oldValue)
	{
		var customer = field.getStore().getById(newValue);
		
		this.grid.setCustomer(customer);
	}
});
